﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PermutationCipher.Models
{
    /// <summary>
    /// 加密类
    /// </summary>
    internal class MyEncode
    {
        /// <summary>
        /// 明文
        /// </summary>
        public string PlainText { get; set; }
        /// <summary>
        /// 密文
        /// </summary>
        public string CipherText { get; set; }
        /// <summary>
        /// 密钥
        /// </summary>
        public string Key { get; set; }
        public void Encode()
        {
            //加密过程
            //确定二维数组的行数和列数
            int line = PlainText.Length / Key.Length;
            int column = Key.Length;
            char[,] twodimarray1 = new char[line, column];
            char[,] twodimarray2 = new char[line, column];
            int[] array = new int[Key.Length];
            char[] ciphertext = new char[PlainText.Length];
            //将明文按密钥给定的列数存入二维数组
            for (int i = 0; i < PlainText.Length; i++)
            {
                twodimarray1[i / Key.Length, i % Key.Length] = PlainText[i];
            }
            //按照密钥交换相应列
            for (int i = 0; i < Key.Length; i++)
            {
                array[i] = Convert.ToInt16(Key[i]) - 49;
                for (int j = 0; j < line; j++)
                {
                    twodimarray2[j, i] = twodimarray1[j, array[i]];
                }
            }
            //将新的二维数组按列存入密文
            for (int i = 0; i < PlainText.Length; i++)
            {
                ciphertext[i] = twodimarray2[i % line, i / line];
            }
            CipherText = new string(ciphertext);
        }

    }

}
